from string import digits

from nctojson.GDFSNcToJson_OEFS_TMP import ReadFromNc
from shapely.geometry import Point
from ConnectJDBCToMySql import *
from netCDF4 import Dataset
import datetime
import geojson
import json
isInList = ["precipitation_type","precipitation_3_hour","precipitation_6_hour","precipitation_12_hour","precipitation_24_hour"]
repless =  ["precipitation_Type","precipitation_3_Hour","precipitation_6_Hour","precipitation_12_Hour","precipitation_24_Hour"]


def ReadFromNc(filePath,layout_data):
    nc_obj = Dataset(filePath)
    # print('--------------------')
    # print(nc_obj)
    # print('--------------------')
    # 纬度
    lat = (nc_obj.variables['lat'][:])
    # 经度
    lon = (nc_obj.variables['lon'][:])
    # 时间（10天，维度为10）
    time = (nc_obj.variables['time'][:])
    if "OEFS_RHMX" in filePath or "OEFS_RHMI" in filePath:
        exec("%s = (nc_obj.variables['%s'][:])" % (layout_data["fileName"], layout_data["get"]))
    else:
        exec("%s = (nc_obj.variables['%s'][:])" % (layout_data["fileName"], layout_data["fileName"]))
    # 需要解析的属性变量在下标为0的位置,属性代表24小时降水，温度等等
    listKeys = list(nc_obj.variables.keys())
    Attr = (nc_obj.variables[listKeys[0]])

    # 获取开始的时间 因为time里面存储是[24,48,...240]  而不是具体的时间
    sinceTimeStr = nc_obj.variables['time'].units.split(" ")[-1]
    sinceTime = datetime.datetime.strptime(sinceTimeStr, '%Y-%m-%dT%H:%M:%SZ')
    # print(sinceTime)
    # newtime = (sinceTime + datetime.timedelta(hours=48)).strftime("%Y-%m-%d %H:%M:%S")
    # print(newtime)
    ncdatadict = dict()
    ncdatadict['lat'] = lat
    ncdatadict['lon'] = lon
    ncdatadict['time'] = time
    ncdatadict['Attr'] = Attr
    ncdatadict['sinceTime'] = sinceTime
    exec("ncdatadict['%s'] = %s" % (layout_data["fileName"], layout_data["fileName"]))
    return ncdatadict


def NcToJson(ncdatadict, jrsjid1, jrsjid2, jrsjid3, AttrName, layout_data):
    try:
        c1 = tosql1()
        c2 = tosql2()
        c3 = tosql3()
        sql4 = UPDATESql(jrsjid1)
        sql5 = UPDATESql(jrsjid2)
        sql6 = UPDATESql(jrsjid3)
        try:
            Lat = ncdatadict['lat']
            Lon = ncdatadict['lon']
            Time = ncdatadict['time']
            Attr = ncdatadict['Attr']
            sinceTime = ncdatadict['sinceTime']
            exec("%s = ncdatadict['%s']" % (layout_data['fileName'], layout_data['fileName']))
            jsondictList = []
            TimeDimension = Attr.shape[0]
            if layout_data['isnot']:
                LatDimension = Attr.shape[2]
                LonDimension = Attr.shape[3]
            else:
                LatDimension = Attr.shape[1]
                LonDimension = Attr.shape[2]
            num = 0
            for i in range(TimeDimension):
                for j in range(LatDimension):
                    for k in range(LonDimension):
                        print(num)
                        num += 1
                        time = (sinceTime + datetime.timedelta(hours=Time[i])).strftime("%Y-%m-%d %H:%M:%S")
                        lat = Lat[j]
                        lon = Lon[k]
                        if layout_data['isnot']:
                            exec("need_data_name = %s[%d, 0, %d, %d]" % (layout_data['fileName'], i, j, k))
                            attr = Attr[i, 0, j, k]
                        else:
                            exec("need_data_name = %s[%d, %d, %d]" % (layout_data['fileName'], i, j, k))
                            attr = Attr[i, j, k]
                        needDataName = locals()["need_data_name"]
                        NcOneObjectDict = dict()
                        NcOneObjectDict['time'] = time
                        NcOneObjectDict['lat'] = round(float(lat), 6)
                        NcOneObjectDict['lon'] = round(float(lon), 6)
                        if layout_data['needDataName'] == "temperature":
                            NcOneObjectDict[layout_data['needDataName']] = round(float(needDataName), 6) - 271.35
                        else:
                            NcOneObjectDict[layout_data['needDataName']] = round(float(needDataName), 6)
                        NcOneObjectDict[AttrName] = 0
                        jsondictList.append(NcOneObjectDict)
                        point = Point((NcOneObjectDict["lon"], NcOneObjectDict["lat"]))
                        geojsondata = geojson.Feature(geometry=point, properties={
                            "value": NcOneObjectDict[layout_data['needDataName']]})
                        # 储存geojson到数据库
                        Sqldate = dict()
                        Sqldate["geoJsonTableName"] = layout_data["geoJsonTableName"]
                        Sqldate["time"] = time
                        Sqldate["geojson"] = json.dumps(geojsondata)
                        Sqldate["jrsjid"] = jrsjid3
                        sql7 = INSERT_geojson(Sqldate)


                        date = dict()
                        field_name = ["time", "lat", "lon", "value", "jrsjid"]
                        value_date = [time, lat, lon, needDataName, jrsjid1]
                        date["table"] = f"tb_gdfs_{layout_data['needDataName']}"
                        for index, field, value in zip(range(1, 6), field_name, value_date):
                            if layout_data["needDataName"] in isInList:
                                date[f"field{index}"] = f"gdfs_{repless[isInList.index(layout_data['needDataName'])]}_{field}"
                            else:
                                date[f"field{index}"] = f"gdfs_{layout_data['needDataName']}_{field}"
                            date[f"value{index}"] = value
                        sql1 = INSERTSql(date)
                        date["value5"] = jrsjid2
                        sql2 = INSERTSql(date)
                        date["value5"] = jrsjid3
                        sql3 = INSERTSql(date)

                        try:
                            c1[1].execute(sql1)
                        except Exception as e:
                            print("GDFSNcToJson_OEFS_TMAX(1) ----- ")

                        try:
                            c2[1].execute(sql2)
                        except Exception as e:
                            print("GDFSNcToJson_OEFS_TMAX(2) ----- ")

                        try:
                            c3[1].execute(sql3)
                        except Exception as e:
                            print("GDFSNcToJson_OEFS_TMAX(3) ----- ")

                        try:
                            c3[1].execute(sql7)
                        except Exception as e:
                            print("GDFSNcToJson_OEFS_TMAX(7) ----- ")

                        # try:
                        #     cursor2.execute(sql8)
                        # except Exception as e:
                        #     print("GDFSNcToJson_OEFS_TMAX(8) ----- ")
                        #
                        # try:
                        #     cursor3.execute(sql9)
                        # except Exception as e:
                        #     print("GDFSNcToJson_OEFS_TMAX(9) ----- ")

            try:
                c1[1].execute(sql4)
            except Exception as e:
                print("GDFSNcToJson_OEFS_TMAX(4) ----- ")

            try:
                c2[1].execute(sql5)
            except Exception as e:
                print("GDFSNcToJson_OEFS_TMAX(5) ----- ")

            try:
                c3[1].execute(sql6)
            except Exception as e:
                print("GDFSNcToJson_OEFS_TMAX(6) ----- ")

            return jsondictList
        except Exception as e:
            print(f"GDFSNcToJson_OEFS_TMP 文件解析异常 ----- {e}")
    except Exception as e:
        print("GDFSNcToJson_OEFS_TMP 数据库连接异常 ----- ")
    finally:
        c1[1].close()
        c1[0].close()
        c2[1].close()
        c2[0].close()
        c3[1].close()
        c3[0].close()


def main(filePath, jrsjid1, jrsjid2, jrsjid3, layout_data):
    ncdatadict = ReadFromNc(filePath, layout_data)
    # Js24代表过去24小时降水
    jsondictList = NcToJson(ncdatadict, jrsjid1, jrsjid2, jrsjid3, 'Js24', layout_data)
